package org.log4jconfig.java.editor.hyperlink;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.hyperlink.IHyperlink;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.log4jconfig.java.editor.util.Logger;

public class LoggerConfigurationHyperlink implements IHyperlink {

	private final IJavaProject javaProject;
	private final IRegion hyperlinkRegion;

	public LoggerConfigurationHyperlink(IRegion hyperlinkRegion,
			IJavaProject javaProject) {
		this.javaProject = javaProject;
		this.hyperlinkRegion = hyperlinkRegion;
	}

	public IRegion getHyperlinkRegion() {
		return hyperlinkRegion;
	}

	public String getHyperlinkText() {
		return "Open log4j.xml config file";
	}

	public String getTypeLabel() {
		return "Jump to log4j.xml config file";
	}

	public void open() {
		// FIXME : incomplete : the following line should be replaced by some
		// code that locates
		// 1 single 'log4j.xml' file from the project's sourcepath or any
		// dependent project....

		// FIXME : move code to LoggerHyperlinkDetector and provide custom hyperlink label. E.g: "Open log4j.xml config file in <project name>"
		// -> several results should be available
		try {
			IResource configFile = null;
			for (IClasspathEntry classpathEntry : javaProject.getResolvedClasspath(true)) {
				
				IPath path = classpathEntry.getPath().append("log4j.xml");
				configFile = javaProject.getProject().getParent().getFile(path);
				if (configFile != null && configFile.exists()) {
					break;
				}
			}
			if (configFile != null && configFile.exists()
					&& configFile instanceof IFile) {
				IWorkbench wb = PlatformUI.getWorkbench();
				IWorkbenchWindow win = wb.getActiveWorkbenchWindow();
				IWorkbenchPage page = win.getActivePage();

				IDE.openEditor(page, (IFile) configFile, true);

			} else {
				Logger
						.warn("Sorry, no 'log4j.xml' file exists in the current project");
			}
		} catch (Exception e) {
			Logger
					.error("Error while trying to open log4j.xml config file:",
							e);
		}
	}

}
